package com.yuedou.api.scheduler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuedou.api.entity.product.ProductOrder;
import com.yuedou.api.entity.wxuser.UserMp;
import com.yuedou.api.service.platfom.ParameterService;
import com.yuedou.api.service.platfom.WxTemplateService;
import com.yuedou.api.service.product.ProductOrderService;
import com.yuedou.api.service.wxuser.UserMpService;
import com.yuedou.api.service.wxuser.UserService;
import com.yuedou.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class DataAnalysis {
    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    @Resource
    private UserMpService userMpService;
    @Resource
    private ParameterService parameterService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private ProductOrderService productOrderService;

    @Value("${web.isLocal}")
    private String isLocal;//图片地址

    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

    //每5分钟执行一次
    @Scheduled(cron = "0 0/2 * * * ?")
    public void ydMpAsync() {
        if(isLocal.equals("0")){
            System.out.println("定时任务执行时间：" + simpleDateFormat.format(new Date()));
//            String accessToken = WxMessage.getACCESSTOKEN(appidMp,secretMp);
//            String access_token = redisTemplate.opsForValue().get("access_token_mp")!=null ? redisTemplate.opsForValue().get("access_token_mp").toString() : null;
//            if(StrUtil.isEmpty(access_token)){
//                access_token = WxMessage.getACCESSTOKEN(appidMp,secretMp);
//                redisTemplate.opsForValue().set("access_token_mp",access_token,3600L, TimeUnit.SECONDS);
//            }
            String access_token = wxTemplateService.getAccessToken(0);// WxMessage.getACCESSTOKEN(appidMp,secretMp);

//            System.out.println("accessToken:" + access_token);
            JSONObject jsonObject = WxMessage.getUserMp(access_token,"");
            if(jsonObject != null){
//                System.out.println("同步公众号用户： " + jsonObject.toString());
                if(jsonObject.containsKey("data") && jsonObject.getJSONObject("data").containsKey("openid")){
                    JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("openid");
                    if(jsonArray != null && jsonArray.size() > 0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            String openid = jsonArray.getStr(i);
                            JSONObject userInfo = WxMessage.getUserMpInfo(access_token,openid);
                            if(userInfo!=null && userInfo.size() > 0){
                                String openId = userInfo.getStr("openid");
                                String unionId = userInfo.getStr("unionid");
                                if(StrUtil.isNotEmpty(openId) && StrUtil.isNotEmpty(unionId)){
                                    QueryWrapper<UserMp> qw = new QueryWrapper<>();
                                    qw.eq("union_id", unionId);
                                    qw.eq("platform","yuedou");
                                    qw.last("limit 1");
                                    UserMp userMp = userMpService.getOne(qw);
                                    if(userMp == null){
                                        userMp = new UserMp();
                                        userMp.setPlatform("yuedou");
                                        userMp.setOpenId(openId);
                                        userMp.setUnionId(unionId);
                                        userMp.setCreateTime(new Date());
                                        boolean bl = userMpService.save(userMp);
                                    }
                                }
//                            else{
//                                userMp.setLastUpdateTime(new Date());
//                                boolean bl = userMpService.updateById(userMp);
//                            }
                            }
                        }
                    }
                }
            }
        }
    }

    //每5分钟执行一次
    @Scheduled(cron = "0 0/2 * * * ?")
    public void bgMpAsync() {
        if(isLocal.equals("0")){
            System.out.println("定时任务执行时间：" + simpleDateFormat.format(new Date()));
            String access_token = wxTemplateService.getAccessToken(3);// WxMessage.getACCESSTOKEN(appidMp,secretMp);

//            System.out.println("accessToken:" + access_token);
            JSONObject jsonObject = WxMessage.getUserMp(access_token,"");
            if(jsonObject != null){
//                System.out.println("同步公众号用户： " + jsonObject.toString());
                if(jsonObject.containsKey("data") && jsonObject.getJSONObject("data").containsKey("openid")){
                    JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("openid");
                    if(jsonArray != null && jsonArray.size() > 0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            String openid = jsonArray.getStr(i);
                            JSONObject userInfo = WxMessage.getUserMpInfo(access_token,openid);
                            if(userInfo!=null && userInfo.size() > 0){
                                String openId = userInfo.getStr("openid");
                                String unionId = userInfo.getStr("unionid");
                                if(StrUtil.isNotEmpty(openId) && StrUtil.isNotEmpty(unionId)){
                                    QueryWrapper<UserMp> qw = new QueryWrapper<>();
                                    qw.eq("union_id", unionId);
                                    qw.eq("platform","bingge");
                                    qw.last("limit 1");
                                    UserMp userMp = userMpService.getOne(qw);
                                    if(userMp == null){
                                        userMp = new UserMp();
                                        userMp.setPlatform("bingge");
                                        userMp.setOpenId(openId);
                                        userMp.setUnionId(unionId);
                                        userMp.setCreateTime(new Date());
                                        boolean bl = userMpService.save(userMp);
                                    }
                                }
//                            else{
//                                userMp.setLastUpdateTime(new Date());
//                                boolean bl = userMpService.updateById(userMp);
//                            }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     *  每2个小时重置一次数据
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void parameterTasks() {
        parameterService.resetParameter(1);
    }

    /**
     *  取消订单(商品订单)
     *  每10分钟执行一次
     *   15分钟之内未支付的订单
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void checkProductOrderCancel() {
        if(isLocal.equals("0")) {
            try {
                Integer[] states = {0, 1};
                QueryWrapper<ProductOrder> qw = new QueryWrapper<>();
                qw.ne("order_type",6);
                qw.in("status", Arrays.asList(states));
                List<ProductOrder> orderList = productOrderService.list(qw);
                if (CollUtil.isNotEmpty(orderList)) {
                    for (ProductOrder productOrder : orderList) {
                        Date createTime = productOrder.getCreateTime();
                        Date checkTime = DateUtil.getAfterSecondsByOld(createTime, 15 * 60);
                        if (new Date().getTime() > checkTime.getTime()) {
                            //取消订单
                            productOrder.setStatus(5);
                            productOrderService.updateById(productOrder);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
